package com.bt.lms.dao.servise.impl;

import com.bt.lms.dao.servise.RightDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 权限dao实现
 *
 * @author 徐大永
 */
public class RightDaoImpl implements RightDao {

    @Override
    public List<Integer> select(String sql, Long id) {

        //要返回的对象
        List<Integer> rightIdS = new ArrayList<>();

        //连接
        Connection connection = UserDaoImpl.pond();
        try {
            //域处理
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setLong(1, id);
            //执行
            ResultSet resultSet = preparedStatement.executeQuery();
            //处理结果集
            while (resultSet.next()) {
                int rightId = resultSet.getInt("right_id");
                rightIdS.add(rightId);
            }
            //关闭资源
            preparedStatement.close();
            connection.close();


            return rightIdS;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public int inserts(String sql, Long id, List<Integer> rights) {

        try {
            //连接
            Connection connection = UserDaoImpl.pond();
            //域处理
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            for (Integer right : rights) {
                preparedStatement.setLong(1, id);
                preparedStatement.setLong(2, right);
                preparedStatement.addBatch();
            }
            //执行
            int[] ints = preparedStatement.executeBatch();
            //关闭资源
            preparedStatement.close();
            connection.close();

            return ints.length;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Integer> selects(String sql, List<Long> roleIds) {

        //要返回的对象
        List<Integer> rightIds = new ArrayList<>();

        try {
            //连接
            Connection connection = UserDaoImpl.pond();
            //域处理
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            //执行
            for (Long roleId:roleIds){
                preparedStatement.setLong(1, roleId);
                ResultSet resultSet = preparedStatement.executeQuery();
                while (resultSet.next()){
                    int rightId = resultSet.getInt(1);
                    rightIds.add(rightId);
                }
            }
            //关闭连接
            preparedStatement.close();
            connection.close();

            return rightIds;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


    }
}
